// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#pragma once

#include <pollux/expression/cast_expr.h>
#include <pollux/functions/prestosql/json/simd_json_wrapper.h>

namespace kumo::pollux {
    /// Custom operator for casts from and to Json type.
    class JsonCastOperator : public exec::CastOperator {
    public:
        bool isSupportedFromType(const TypePtr &other) const override;

        bool isSupportedToType(const TypePtr &other) const override;

        void castTo(
            const BaseVector &input,
            exec::EvalCtx &context,
            const SelectivityVector &rows,
            const TypePtr &resultType,
            VectorPtr &result) const override;

        void castTo(
            const BaseVector &input,
            exec::EvalCtx &context,
            const SelectivityVector &rows,
            const TypePtr &resultType,
            VectorPtr &result,
            const std::shared_ptr<exec::CastHooks> &hooks) const override;

        void castFrom(
            const BaseVector &input,
            exec::EvalCtx &context,
            const SelectivityVector &rows,
            const TypePtr &resultType,
            VectorPtr &result) const override;

    private:
        template<TypeKind kind>
        void castFromJson(
            const BaseVector &input,
            exec::EvalCtx &context,
            const SelectivityVector &rows,
            BaseVector &result) const;

        mutable melon::once_flag initializeErrors_;
        mutable std::exception_ptr errors_[simdjson::NUM_ERROR_CODES];
        mutable std::string paddedInput_;
    };
} // namespace kumo::pollux
